const Koa = require('koa')
const app = new Koa()
const cors=require('koa2-cors')
app.use(cors());
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session=require('koa-session2')
const wechatapi = require('co-wechat-api')


const websocker=require('./routes/websocket/socketserver.js')
//20220213更改为casbin基于角色的权限验证
// const auth=require('./jwtauth.js')
const auth=require('./casbinAuth')
const db=require('./cfg/dbconfig');
const wechatconfig = require('./cfg/wechatconfig.js')

var access_token = null;
var api = new wechatapi(
  wechatconfig.wechatauth.appid,
  wechatconfig.wechatauth.appsecret,
  null,
  function (token) {
      access_token = token
  }
);

//const index = require('./routes/index')
//const users = require('./routes/users')
const sys=require('./routes/sys/index');
const mark=require('./routes/sys/mark');
const graduate=require('./routes/sys/graduate');
const transschool=require('./routes/sys/transschool')
const typekey=require('./routes/typekey/index');
const sitenav=require('./routes/SiteNav/index')
const test=require('./routes/test');
const wechat=require('./routes/wechat/index')
const homeinfo=require('./routes/wechat/homeinfo')
const graduateinfo=require('./routes/wechat/graduateinfo')
const newstudentreg=require('./routes/wechat/newstudentreg')
const student=require('./routes/wechat/student.js')
const website=require('./routes/glxxweb/index.js')
const vod=require('./routes/glxxvod/index')
const interest=require('./routes/wechat/interest')
const afterclasssrv=require('./routes/wechat/afterclassrv.js')
const loginqrcode=require('./routes/sys/loginqrcode.js')
const afterclasssrv2=require('./routes/sys/afterclasssvr.js')
const notice=require("./routes/wechat/notice.js")
const account=require("./routes/sys/account.js")
const sys_notice=require("./routes/sys/notice.js")
const comm=require("./routes/comm.js")
const afterClasSrvComm=require("./routes/afterClasSrvComm.js")



// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
//session
app.use(session())
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'nunjucks'
}))


// app.use(cors({
//   // origin:"*",
//   //origin://"*",//"http://mxthink.cross.echosite.cn",
//       //return 'http://localhost:8080'; / 这样就能只允许 http://localhost:8080 这个域名的请求了
//   exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
//   maxAge: 5,
//   credentials: true,
//   allowMethods: ['GET', 'POST', 'DELETE','OPTIONS'],
//   allowHeaders: ['Content-Type', 'Authorization', 'Accept','Keep-Alive'],
// }))

//20220213更改为casbin基于角色的权限验证
// let notcheckpath=[
//   '/wechatforsvr/getnews',
//   '/wechatforsvr/config',
//   '/wechatforsvr/sendtemplatemsg',
//   '/wechatforsvr/dakamsg',
//   '/wechatforsvr/newstu',
//   '/wechatforsvr/jsconfig/',
//   '/wechatforsvr/binder3',
//   '/wechatforsvr',
//   '/wechatforsvr/t',
//   '/sitenav/getlinks',
//   '/sys/login',
//   '/typekey/getalltklesson',
//   '/typekey/getlessonbyid',
//   '/typekey/gettkrecordrank',
//   '/login/getqr',
//   '/login/getwsc',
//   '/login',
//   '/sys/search',
//   '/sys/unbinderwechat',
//   '/transschool/gettransschoolinfo',
//   '/transschool/save',

  // '/sys/afterclasssvr/getstudentinfo',
  // '/sys/afterclasssvr/getallstudentofclass',
//   '/sys/importaccount',
//   '/wechatforsvr/delmenu',
//   '/wechatforsvr/creatmenu',
//   '/sys/account/getGradeAndClass',
//   '/sys/account/getStudentlistByClassNo',
//   '/sys/account/getStudentlistByGrade',
//   '/sys/account/getClassByGrade',
// ];
// let notcheckdir=['/test','/upload']

//20220213更改为casbin基于角色的权限验证
// app.use(auth({ notcheckpath: notcheckpath,notcheckdir:notcheckdir }));
app.use(auth.authorisation())
app.use(websocker)

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})



//微信接口初始化
app.use(async (ctx, next) => {
  ctx.state.wechatApi = api;
  ctx.state.wechatAccessToken = access_token;
  ctx.state.noticeStatus = new Map([
    ["unsend", "1未发送"],
    ["receTrue", "4接收成功"],
    ["receFalse", "3接收失败"],
    ["sign", "4已签"]
  ]),
  ctx.state.aftclssvrStatus=new Map([
    ["unAllot","未分配"],
    ["allot","已分配"],
    ["requestQuit","申请退出"],
    ["quit","退出"],
    ["requestIn","再入申请"],
    ['lock','已锁定']
  ])
    await next();
})


//拦截请求
// app.use(async (ctx,next)=>{
//   console.log('app拦截的访问:' + ctx.request.href)
//   if (ctx.header.authorization) {
//     try {
//         //验证token合法性
//         let token = await jwt.verify(ctx.header.authorization, sitecfg.tokenKey);
//         ctx.request.token = token;
//     } catch (err) {
//         ctx.body = { vali: false, message: "验证token时出错：[" + err + "]程序终止!" };
//         return;
//     }
// }
//   await next()
// })

//koa-body
// app.use(koabody({
//   multipart:true,
//   formidable:{
//     maxFileSize:10*1024*1024
//   }
// }))

// routes
// app.use(index.routes(), index.allowedMethods())
// app.use(users.routes(), users.allowedMethods())
app.use(sys.routes(),sys.allowedMethods())
app.use(typekey.routes(),typekey.allowedMethods())
app.use(sitenav.routes(),sitenav.allowedMethods())
app.use(mark.routes(),mark.allowedMethods())
app.use(graduate.routes(),mark.allowedMethods())
app.use(wechat.routes(),wechat.allowedMethods())
app.use(homeinfo.routes(),homeinfo.allowedMethods())
app.use(graduateinfo.routes(),graduateinfo.allowedMethods())
app.use(newstudentreg.routes(),newstudentreg.allowedMethods())
app.use(test.routes(),test.allowedMethods())
app.use(transschool.routes(),transschool.allowedMethods())
app.use(student.routes(),student.allowedMethods())
app.use(website.routes(),sys.allowedMethods())
app.use(vod.routes(),vod.allowedMethods())
app.use(interest.routes(),interest.allowedMethods())
app.use(afterclasssrv.routes(),afterclasssrv.allowedMethods())
app.use(loginqrcode.routes(),loginqrcode.allowedMethods())
app.use(afterclasssrv2.routes(),afterclasssrv2.allowedMethods())
app.use(notice.routes(),notice.allowedMethods())
app.use(account.routes(),account.allowedMethods())
app.use(sys_notice.routes(),sys_notice.allowedMethods())
app.use(comm.routes(),comm.allowedMethods())
app.use(afterClasSrvComm.routes(),afterClasSrvComm.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
